package cn.faifai.tagapi.service.BackgroundServices;

import cn.faifai.tagapi.config.HardLinksConfig;
import cn.faifai.tagapi.entity.IFile;
import cn.faifai.tagapi.entity.Tag;
import cn.faifai.tagapi.repository.FileUrlRepository;
import cn.faifai.tagapi.repository.TagRepository;
import cn.hutool.core.collection.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Set;


@Service
public class FileUrlClearService {
    @Autowired
    private FileUrlRepository fileUrlRepository;
    @Autowired
    private TagRepository tagRepository;

    @Scheduled(cron = "0 0 0 * * ?")
    public void clearFileUrl(){
        // 分页查询文件记录
        Integer pageSize = 100;
        Integer pageNum = 0;
        while (true){
            Pageable page = Pageable.ofSize(pageSize).withPage(pageNum);
            Page<IFile> list = fileUrlRepository.findAll(page);
            // 5天前 并转成date
            LocalDate localDate = LocalDate.now().minusDays(5);
            Date fiveDayAgo = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
            for (IFile item : list){
                // 最后一次修改是5天前
                List<Tag> tags = tagRepository.findByIFilesOsFileId(item.getOsFileId());
                if (CollectionUtil.isEmpty(tags) /*&& item.getLastModifiedAt().before(fiveDayAgo)*/){
                    String hardlink = item.getDisk() + "\\" + HardLinksConfig.DIRECTORY + "\\"+ item.getId() + "." + item.getSuffix();
                    File file = Paths.get(hardlink).toFile();
                    if (file.exists()){
                        file.delete();
                        fileUrlRepository.delete(item);
                    }
                }
            }
            pageNum++;
            if (pageNum > list.getTotalPages()){
                break;
            }
        }
    }
}
